window.onload = function() {
    // 存储商家名称,购买信息到 localStorage
    const shopName = document.getElementById("shop-name").innerHTML;
    localStorage.setItem("shopName", shopName);

    // 获取按钮和元素
    const plusButtons = document.querySelectorAll('.pls');
    const minusButtons = document.querySelectorAll('.min');
    const numElements = document.querySelectorAll('.num');
    const priceElements = document.querySelectorAll('.price');
    const totalElements = document.getElementById('tot-money');

    let formal_goto_pay = document.getElementById("goto_pay").innerHTML;

    // 增加按钮逻辑
    plusButtons.forEach((button, index) => {
        button.onclick = function() {
            let num = parseInt(numElements[index].innerHTML);
            num++;
            let price = parseInt(priceElements[index].innerHTML);
            let total = parseInt(totalElements.innerHTML);
            total += price;
            totalElements.innerHTML = total;
            numElements[index].innerHTML = num;

            if (num == 1) {
                minusButtons[index].style.display = "";
                numElements[index].style.display = "";
            }
            if (totalElements.innerHTML >= parseInt(document.getElementById("diliver_need").innerHTML)) {
                document.getElementById("goto_pay").innerHTML = "去支付";
            }
        };
    });

    // 减少按钮逻辑
    minusButtons.forEach((button, index) => {
        button.onclick = function() {
            let num = parseInt(numElements[index].innerHTML);
            if (num > 0) {
                num--;
                let price = parseInt(priceElements[index].innerHTML);
                let total = parseInt(totalElements.innerHTML);
                total -= price;
                totalElements.innerHTML = total;
            }
            numElements[index].innerHTML = num;
            if (num == 0) {
                minusButtons[index].style.display = "none";
                numElements[index].style.display = "none";
            }
            if (totalElements.innerHTML >= parseInt(document.getElementById("diliver_need").innerHTML)) {
                document.getElementById("goto_pay").innerHTML = "去支付";
            } else if (totalElements.innerHTML < parseInt(document.getElementById("diliver_need").innerHTML)) {
                document.getElementById("goto_pay").innerHTML = formal_goto_pay;
            }
        };
    });

    // 跳转到 checkInfo.html 的逻辑
    const tans_to_business_bt = document.querySelectorAll('.shopcar-bottom-right');
    tans_to_business_bt.forEach((button) => {
        button.onclick = function() {
            if (document.getElementById("goto_pay").innerHTML == "去支付") {
                localStorage.setItem("money",totalElements.innerHTML);
                console.log("Button clicked, redirecting to checkInfo.html");
                window.location.href = "checkInfo.html";
            }
        };
    });

};